<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/12
  Time: 17:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>销售对账</title>
    <jsp:include page="../headPage.jsp"></jsp:include>
    <%String j=request.getParameter("id"); %>
    <script type="text/javascript">
    
    function toastrStyle(){
		toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-top-center",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "5000",
            "hideDuration": "1000",
            "timeOut&quot": "100000",
            "extendedTimeOut": "0",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }; 
	}
    
        $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();

            //行点击事件
            $('#tb_departments').on('click-row.bs.table', function (e, row, element) {
            	console.log(row);
            	var recent=$('#recent option:selected').val()
            	var beginDate=$('#beginDate').val();
            	initBottomTable(row.pid,recent,beginDate);
            });
        });

        function setAmount(data,price,lastMonthQ,monthQ){
        	var id=data.id.substring(data.id.length-1,data.id.length);
        	var reg=/^[1-9]\d*$|^0$/;
        	if(reg.test(data.value)){
        		if(data.value>lastMonthQ+monthQ){
        			toastrStyle();
            		toastr.warning('结算数量不能大于期初和出库数量之和');
            		$('#settlementQ'+id).val(lastMonthQ+monthQ);
            		$('#settlementP'+id).val((lastMonthQ+monthQ)*price);
            		$('#balanceQ'+id).val(0);
            		$('#balanceP'+id).val(0);
        		}else{
                	var lastMonthP=data.value*price;
                	var num=lastMonthQ+monthQ-data.value;
                	$('#settlementP'+id).val(lastMonthP);
            		$('#balanceQ'+id).val(num);
            		$('#balanceP'+id).val(num*price);
        		}
        	}else{
        		toastrStyle();
        		toastr.warning('只能输入正整数');
        		var num=data.value.split('.')[0];
        		$('#'+data.id).val(num);
        		$('#settlementP'+id).val(num*price);
        		$('#balanceQ'+id).val(lastMonthQ+monthQ-num);
        		$('#balanceP'+id).val((lastMonthQ+monthQ-num)*price);
        	}
        }

        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_departments').bootstrapTable({
                    url: '${pageContext.request.contextPath }/hpf/reconciliationList.do',         //请求后台的URL（*）
                    method: 'post',                      //请求方式（*）
                    contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 20, 30],        //可供选择的每页的行数（*）
                    strictSearch: true,
                    clickToSelect: true,                //是否启用点击选中行
                    height: 400,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
                    //showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    //detailView: false,                   //是否显示父子表
                    columns: [[
						{
						    checkbox: true
						},
                        {
                            field: 'id',
                            title: 'ID',
                            visible: false,
                        },
                        {
                            field: 'cartype',
                            title: '车种',
                            valign: "middle",
                            align: "center",
                        }, {
                            field: 'num',
                            title: '品编',
                            valign: "middle",
                            align: "center",
                        }, {
                            field: 'name',
                            title: '品名',
                            valign: "middle",
                            align: "center",
                        }, {
                            field: 'remark8',
                            title: '单价',
                            valign: "middle",
                            align: "center",
                        }, /* {
                            field: 'dateMonth',
                            title: '时间',
                            valign: "middle",
                            align: "center",
                        }, */ {
                            field: 'lastMonthQ',
                            title: '期初结存数量',
                            valign: "middle",
                            align: "center",
                        }, {
                            field: 'lastMonthP',
                            title: '期初结存金额',
                            valign: "middle",
                            align: "center",
                        	formatter: function (value, row, index) {
	                            if(row.planCount>0){
	                            	return row.lastMonthQ*row.remark8;
	                            }else{
	                            	return 0;
	                            }
                        	}
                        }, {
                            field: 'monthQ',
                            title: '本期出库',
                            valign: "middle",
                            align: "center",
                            //colspan:8,
                        }, {
                            field: 'monthP',
                            title: '本期出库金额',
                            valign: "middle",
                            align: "center",
                            formatter: function (value, row, index) {
                                if(row.monthQ>0){
                                	return row.monthQ*row.remark8;
                                }else{
                                	return 0;
                                }
                            }
                        }, {
                            field: 'monthSettlementQ',
                            title: '本期结算数量',
                            valign: "middle",
                            align: "center",
                            formatter: function (value, row, index) {
                                if(row.monthSettlementQ>=0){
                                	return '<input type="number" min="0" oninput="setAmount(this,'+row.remark8+','+row.lastMonthQ+','+row.monthQ+')" class="form-control" id="settlementQ'+row.pid+'" value="'+row.monthSettlementQ+'">'
                                }else{
                                	return '<input type="number" min="0" oninput="setAmount(this,'+row.remark8+','+row.lastMonthQ+','+row.monthQ+')" class="form-control" id="settlementQ'+row.pid+'">'
                                }
                            }
                        }, {
                            field: 'monthSettlementP',
                            title: '本期结算金额',
                            valign: "middle",
                            align: "center",
                            formatter: function (value, row, index) {
                                if(row.monthSettlementP>=0){
                                	return '<input type="number" readonly min="0" class="form-control" id="settlementP'+row.pid+'" value="'+row.monthSettlementP+'">'
                                }else{
                                	return '<input type="number" readonly min="0" class="form-control" id="settlementP'+row.pid+'">'
                                }
                            }
                        }, {
                            field: 'closingBalanceQ',
                            title: '期末结存数量',
                            valign: "middle",
                            align: "center",
                            formatter: function (value, row, index) {
                                if(row.closingBalanceQ>=0){
                                	return '<input type="number" readonly min="0" class="form-control" id="balanceQ'+row.pid+'" value="'+row.closingBalanceQ+'">'
                                }else{
                                	return '<input type="number" readonly min="0" class="form-control" id="balanceQ'+row.pid+'">'
                                }
                            }
                        }, {
                            field: 'closingBalanceP',
                            title: '期末结存金额',
                            valign: "middle",
                            align: "center",
                            formatter: function (value, row, index) {
                                if(row.closingBalanceP>=0){
                                	return '<input type="number" readonly min="0" class="form-control" id="balanceP'+row.pid+'" value="'+row.closingBalanceP+'">'
                                }else{
                                	return '<input type="number" readonly min="0" class="form-control" id="balanceP'+row.pid+'">'
                                }
                            }
                        }/* , {
                            field: 'aa',
                            title: "结算",
                            formatter: function (value, row, index) {
                                return '<a href="#" onclick="jiesuan(' + index + ')">结算</a>'
                            }
                        } */
                    ]]
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset / params.limit + 1,  //页码
                    demandDate: $("#demandDate_serch").val(),
                    produceStatus: $("#produceStatus_serch").val(),
                    outLibraryStatus: $("#outLibraryStatus_serch").val(),
                    //customerId: $("#customerId_serch").val(),
                    customerId: <%= j%>,
                    entryPerson: $("#entryPerson_serch").val(),
                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {

            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };
            return oInit;
        };
    </script>
</head>
<body>
<div class="panel-body" style="padding-bottom:0px;">
    <div class="panel panel-default">
    	<div class="panel-heading">查询条件</div>
        <div class="panel-body">
            <form id="formSearch" class="form-horizontal">
                <label class="control-label col-sm-1">日期:</label>
                <!-- <div class="col-sm-1">
                    <select id="recent" name="recent"
                            class="selectpicker show-tick form-control" data-live-search="false">
                        <option value="0">无</option>
                        <option value="1">最近一天</option>
                        <option value="7">最近一星期</option>
                        <option value="30">最近一个月</option>
                    </select>
                </div> -->
                <!-- <label class="control-label col-sm-1" for="beginDate" style="width: 30px;">从</label> -->
                <div class="col-sm-2">
                    <input type="text" name="beginDate" id="beginDate" placeholder="yyyy-mm" class="beginDate form-control">
                </div>
                <!-- <label class="control-label col-sm-1" for="endDate"
                       style="width: 30px;padding-left: 0px;">至</label>
                <div class="col-sm-2" style="padding-left: 0px;">
                    <input type="text" name="endDate" id="endDate" lay-verify="date"
                           placeholder="yyyy-mm-dd"
                           autocomplete="off" class="layui-input form-control"
                           onclick="layui.laydate({elem: this})">
                </div> -->
                <div class="col-sm-1" style="text-align:left;">
                    <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>
                </div>
            </form>
        </div>
    </div>

    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>保存对账信息
        </button>
        <button id="btn_addAmount" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>新增收款金额
        </button>
        <!-- <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>打印
        </button>
        <button id="btn_jiesuanAll" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>所有结算
        </button> -->
    </div>

    <!--        表格           -->
    <table id="tb_departments" style="font-size: 14px;"></table>

    <div id="bottomTableDiv"></div>
	
	<div class="modal fade" id="addAmountModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
		<!-- data-backdrop="static" data-keyboard="false" -->
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="addModalLabel">新增客户信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="addAmountForm" method="post">
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">客户名称</label>
							<div class="col-sm-9">
								<select id="customerId" name="customerId" class="form-control" style="width: 85%;"></select>
							</div>
						</div>
						<div class="form-group">
							<label for="type" class="col-sm-3 control-label">收款日期</label>
							<div class="col-sm-9">
								<input type="text" id="receiptDate" name="receiptDate" class="form-control form_datetime" style="width: 85%;" placeholder="请输入收款日期..." data-bv-notempty="true">
							</div>
						</div>
						<div class="form-group">
							<label for="linkman" class="col-sm-3 control-label">收款金额</label>
							<div class="col-sm-9">
								<input type="number" id="amount" min="0" name="amount" class="form-control" style="width: 85%;" placeholder="请输入收款金额..." data-bv-notempty="true">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
							<button type="submit" class="btn btn-primary">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>
</body>


<script>

    $("#btn_jiesuanAll").click(function () {
        //进入后台结算  完成后需要刷新表格
        $.ajax({
            url: "${pageContext.request.contextPath }/yzl/ReconciliationJs.do?id="+ <%= j%>,//对账结算
            type: "GET",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                /*if(data == 1){
                    alert("操作成功！");
                }else{
                    alert("操作失败！");
                }*/
            }
        })
    })

   function jisuangb() {

       var index = $("#jsindex").val();
       var row = $('#tb_departments').bootstrapTable('getData')[index];
       var jsSum = $("#jsSum").val();
       row.monthSettlementQ = jsSum;
       $.ajax({
           url: "${pageContext.request.contextPath }/yzl/reconciliationJsOne.do",//对账结算
           type: "POST",
           data: row,
           success: function (data) {
               if(data == 1){
            	   toastr.warning("操作成功！");
                   //刷新表格
                   $("#tb_departments").bootstrapTable('refresh', {url: '${pageContext.request.contextPath }/yzl/reconciliationList.do'});
               }else{
            	   toastr.warning("操作失败！");
               }
               $('#jiesuanModel').modal('hide')
           }
       })

   }




    //点击结算
    function jiesuan(index) {

        $('#jiesuanModel').modal({
            keyboard: true,
        })
        $("#jsindex").val(index);
    }

    $("#btn_query").click(function (){
    	//var recent=$('#recent option:selected').val()
    	var beginDate=$('#beginDate').val();
    	//var endDate=$('#endDate').val();
    	//window.location.href = "${pageContext.request.contextPath }/pages/yzlERP/salesReconciliation/salesReconciliation.jsp";
    	$("#tb_departments").bootstrapTable('refresh', {url: '${pageContext.request.contextPath }/hpf/reconciliationList.do?beginDate='+beginDate});
    })

    //点击查询 重新请求  刷新表格
    function refreshAjax() {
        $("#tb_departments").bootstrapTable('refresh', {url: '${pageContext.request.contextPath }/hpf/reconciliationList.do'});
    }
    
  	//保存对账信息
    $('#btn_add').on('click', function () {

    	var date=new Date;
    	var year=date.getFullYear(); 
    	var month=date.getMonth()+1;
    	var nowDate=year+"-"+month;
    	//必须选中一条数据
    	var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
		console.log(checkedItems);
        if(checkedItems.length == 0){
        	toastrStyle();
           	toastr.warning('请选择一行信息');
        }else{
        	for(var i=0;i<checkedItems.length;i++){
        		var settlementQ = $("#settlementQ"+checkedItems[i].pid).val();
        		var settlementP = $("#settlementP"+checkedItems[i].pid).val();
        		var balanceQ = $("#balanceQ"+checkedItems[i].pid).val();
        		var balanceP = $("#balanceP"+checkedItems[i].pid).val();
        		var dateMonth=checkedItems[i].dateMonth;
        		if(dateMonth.indexOf(nowDate) == -1){
        			toastrStyle();
                   	toastr.warning('只能修改当月结算数量');
        			return false;
        		}else{
        			if(settlementQ==''){
            			toastrStyle();
                       	toastr.warning('请输入结算数量');
                       	return false;
            		}else{
            			checkedItems[i].monthSettlementQ=settlementQ;
            			checkedItems[i].monthSettlementP=settlementP;
            			checkedItems[i].closingBalanceQ=balanceQ;
            			checkedItems[i].closingBalanceP=balanceP;
            		}
        		}
        	}
        	console.log(checkedItems);
        	var obj = { productors : checkedItems };
        	$.ajax({
	            url : "${pageContext.request.contextPath }/hpf/addReconciliationFrom.do",
	            type : "POST",
	            data : JSON.stringify(obj),
	            contentType: "application/json; charset=utf-8",
	            dataType : "json",
	            success : function(data){
	                if(data == 1){
	                	toastrStyle();
	                    toastr.success("保存成功！");
	                    setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
	                		refreshAjax();
						},2000);
	                }else{
	                	toastrStyle();
	                	toastr.warning("保存失败！");
	                }
	            }
	        })
        }
	});
  	
  	//新增收款金额
  	$('#btn_addAmount').on('click', function () {
  		$("#addAmountForm")[0].reset();
  		$("#customerId").empty();
  		$(function() {
        	//执行后台
            $.ajax({
                url: "${pageContext.request.contextPath}/hpf/customerAllList.do",
                type: "post",
                success: function (data) {
                	//var row = data.rows;
                	for(var i=0;i<data.length;i++){
                    	//console.log(data[i]);
                		//添加option
                    	$("#customerId").append('<option value="'+data[i].id+'">' + data[i].name + '</option>');
                	}
                }
            })
		})
  		$('#addAmountModal').modal({
            keyboard: true,
        })
        $(function() {
			var layerTips = parent.layer === undefined ? layui.layer : parent.layer
			$("#addAmountForm").bootstrapValidator({
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					customerID : {
						validators : {
							notEmpty : {
								message : '请选择客户名称'
							},
						},
					},
					receiptDate : {
						validators : {
							notEmpty : {
								message : '收款日期不能为空'
							},
						},
					},
					amount : {
						validators : {
							notEmpty : {
								message : '收款金额不能为空'
							},
						},
					},
				},
			}).on('success.form.bv',function() {
				var customerId = $('#customerId').val();
				var receiptDate = $('#receiptDate').val();
				var amount = $('#amount').val();
				var obj = {
			            customerId : customerId,
			            receiptDate : receiptDate,
			            amount : amount
			        };
				$.ajax({
					type : 'post',
					url : '${pageContext.request.contextPath }/hpf/addReceiptAmount.do',
					data : JSON.stringify(obj),
					contentType: "application/json; charset=utf-8",
		            dataType : "json",
		            async:false,
					success : function(data) {
						if (data==1) {
							toastrStyle();
		                    toastr.success("添加成功！");
		                    $('#addAmountModal').modal({
		                        keyboard: false,
		                    })
						} else {
							toastrStyle();
		                    toastr.warning("添加失败！");
						}
					}
				});
			});
		});
  	})

</script>


<script>
    //底部详情列表初始化
    function initBottomTable(pid,recent,beginDate,endDate){
        var $bottomTableDiv = $("#bottomTableDiv");
        console.log($bottomTableDiv);
        if($bottomTableDiv.find("table").length > 0){
            url = "${pageContext.request.contextPath }/hpf/reconciliationXQ.do?pid="+pid+"&beginDate="+beginDate;
            $("#tb_everyMonth").bootstrapTable('refresh', {url: url});
            //$bottomTableDiv.empty();
        }else{
            console.log("else-------------------------------------else");
            var table = '<table id="tb_everyMonth"  style="font-size: 14px;"></table>'
            $bottomTableDiv.append(table);

            $('#tb_everyMonth').bootstrapTable({
                dataType: "json",
                method: 'get',
                contentType: "application/x-www-form-urlencoded",
                cache: false,
                url: "${pageContext.request.contextPath }/hpf/reconciliationXQ.do?pid="+pid+"&beginDate="+beginDate,
                //url: "/pages/yzlERP/data/everyMonth.json",
                height:300,
                columns: [
                    [{
                        field: 'outDate',
                        title: '时间',
                        valign: "middle",
                        align: "center"
                    },{
                        field: 'outQ',
                        title: '本期出库数量',
                        valign: "middle",
                        align: "center"
                    }]
                ]
            });
        }


    }
    /* laydate.render({
  	  elem: '#beginDate'
  	  ,type: 'month'
  	  ,max: 0
  	}); */
  	$(".beginDate").datetimepicker({
  		language:  'zh-CN',
        format: 'yyyy-mm',
        autoclose: true,
        todayBtn: true,
        startView: 'year',
        minView:'year',
        maxView:'decade',
        endDate: new Date()
 	})
  	$(".form_datetime").datetimepicker({
  		 format: "yyyy-mm-dd",
  		 autoclose: true,
  		 todayBtn: true,
  		 todayHighlight: true,
  		 showMeridian: true,
  		 pickerPosition: "bottom-left",
  		 language: 'zh-CN',//中文，需要引用zh-CN.js包
  		 startView: 2,//月视图
  		 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
  	}).on('hide',function(e) {  
        //e.preventDefault();		//e.preventDefault()阻止事件默认行为。
    	e.stopPropagation(); //e.stopPropagation()阻止事件冒泡
    	$('#addAmountForm').data('bootstrapValidator')  
        .updateStatus('receiptDate', 'NOT_VALIDATED',null)  
        .validateField('receiptDate');  
	});
</script>

<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
          	laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function (data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });


</script>

</html>
